package com.naqiang.electronicdictionary.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.naqiang.electronicdictionary.R;
import com.naqiang.electronicdictionary.adapter.TranslateAdapter;
import com.naqiang.electronicdictionary.application.MyApplication;
import com.naqiang.electronicdictionary.data.DBOperationImpl;
import com.naqiang.electronicdictionary.entity.TranslateData;
import com.naqiang.electronicdictionary.entity.UnKnowWord;
import com.naqiang.electronicdictionary.manager.SharedPreferencesManager;
import com.naqiang.electronicdictionary.util.DateUtil;
import com.naqiang.electronicdictionary.util.LogUtil;
import com.naqiang.electronicdictionary.util.ThreadPoolProxyFactory;
import com.naqiang.electronicdictionary.util.ToastUtil;
import com.naqiang.electronicdictionary.widget.SwListDialog;
import com.youdao.sdk.app.Language;
import com.youdao.sdk.app.LanguageUtils;
import com.youdao.sdk.common.Constants;
import com.youdao.sdk.ydonlinetranslate.Translator;
import com.youdao.sdk.ydtranslate.Translate;
import com.youdao.sdk.ydtranslate.TranslateErrorCode;
import com.youdao.sdk.ydtranslate.TranslateListener;
import com.youdao.sdk.ydtranslate.TranslateParameters;

import java.util.ArrayList;
import java.util.List;

/**
 * Author by naqiang, Date on 2019\3\16 0016.
 * PS: Not easy to write code, please indicate.
 * 在线翻译的Fragment
 */
public class OnlineTranslateFragment extends BaseFragment implements TranslateAdapter.OnTranslateClickListener {

    // 查询列表
    private ListView translateList;

    private TranslateAdapter adapter;
    private List<TranslateData> list = new ArrayList<TranslateData>();
    private List<Translate> trslist = new ArrayList<Translate>();
    private ProgressDialog progressDialog = null;
    private Handler waitHandler = new Handler();

    private EditText fanyiInputText;

    private InputMethodManager imm;

    private TextView fanyiBtn;

    TextView languageSelectFrom;

    TextView languageSelectTo;

    private Translator translator;

    private DBOperationImpl dbOperation;

    @Override
    protected int setView() {
        return R.layout.fragment_online_translate;
    }

    @Override
    protected void initView(View view) {
        dbOperation = DBOperationImpl.getInstance();
        fanyiInputText = (EditText) view.findViewById(R.id.fanyiInputText);
        fanyiBtn = (TextView) view.findViewById(R.id.fanyiBtn);
        translateList = (ListView) view.findViewById(R.id.commentList);
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        View myview = this.getLayoutInflater().inflate(R.layout.translate_head,
                translateList, false);
        translateList.addHeaderView(myview);
        adapter = new TranslateAdapter(getActivity(), list, trslist);
        adapter.setOnTranslateClickListener(this);
        translateList.setAdapter(adapter);
        languageSelectFrom = (TextView) view.findViewById(R.id.languageSelectFrom);
        languageSelectTo = (TextView) view.findViewById(R.id.languageSelectTo);
        refreshLanguageChooser();
    }

    public void refreshLanguageChooser(){
        String from = (String) SharedPreferencesManager.getSingleTon().getSharedPreference(SharedPreferencesManager.KEY_FROM, "中文");
        String to = (String) SharedPreferencesManager.getSingleTon().getSharedPreference(SharedPreferencesManager.KEY_TO, "英文");
        languageSelectFrom.setText(from);
        languageSelectTo.setText(to);
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.fanyiBtn:
                query();
                break;
            case R.id.languageSelectFrom:
                selectLanguage(languageSelectFrom);
                break;
            case R.id.languageSelectTo:
                selectLanguage(languageSelectTo);
                break;
        }
    }

    @Override
    public void setListener() {
        fanyiBtn.setOnClickListener(this);
        languageSelectFrom.setOnClickListener(this);
        languageSelectTo.setOnClickListener(this);
    }

    @Override
    public void doWork() {

    }

    //当翻译结果被点击回调此方法
    @Override
    public void onTranslateClick(int position) {
        Translate tr = trslist.get(position);
        //TranslateDetailActivity.open((Activity)context, bean, tr);
    }

    //当加入单词本几个字被点击回调此方法
    @Override
    public void onAddNoteClick(final int position,final TextView textView) {

        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(new Runnable() {
            @Override
            public void run() {
                TranslateData bean = list.get(position);
                UnKnowWord unKnowWord = new UnKnowWord();
                unKnowWord.fromLanguage = languageSelectFrom.getText().toString();
                unKnowWord.toLanguage = languageSelectTo.getText().toString();
                unKnowWord.fromWord = bean.getQuery();
                unKnowWord.toWord = TextUtils.isEmpty(bean.translates()) ? bean.means() : bean.translates();
                unKnowWord.addTime = DateUtil.getCurrentDateStr();
                boolean flag = dbOperation.insertUnKnowWord(unKnowWord);
                if(flag && textView!=null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setVisibility(View.GONE);
                        }
                    });
                }
               // LogUtil.i("unKnowWord.toString", unKnowWord.toString()+flag);
            }
        });
    }


    /**
     * 选择语种
     *
     * @param languageSelect
     */
    private void selectLanguage(final TextView languageSelect) {
        final String str[] = LanguageUtils.langs;
        List<String> items = new ArrayList<String>();
        for (String s : str) {
            items.add(s);
        }
        SwListDialog exitDialog = new SwListDialog(getActivity(), items);
        exitDialog.setItemListener(new SwListDialog.ItemListener() {

            @Override
            public void click(int position, String title) {

                String language = languageSelect.getText().toString();
                languageSelect.setText(title);
                String from = languageSelectFrom.getText().toString();
                String to = languageSelectTo.getText().toString();
                String lan = "中文";
//                if (!from.contains(lan) && !to.contains(lan)
//                        && !to.contains("自动") && !from.contains("自动")) {
//                    ToastUtils.show("源语言或者目标语言其中之一必须为" + lan);
//                    languageSelect.setText(language);
//                    return;
//                }
            }
        });
        exitDialog.show();
    }

    /**
     * 翻译查询方法
     */
    private void query() {
        showLoadingView("正在查询");

        // 源语言或者目标语言其中之一必须为中文,目前只支持中文与其他几个语种的互译
        String from = languageSelectFrom.getText().toString();
        String to = languageSelectTo.getText().toString();
        final String input = fanyiInputText.getText().toString();

        Language langFrom = LanguageUtils.getLangByName(from);
        // 若设置为自动，则查询自动识别源语言，自动识别不能保证完全正确，最好传源语言类型
        // Language langFrosm = LanguageUtils.getLangByName("自动");

        Language langTo = LanguageUtils.getLangByName(to);

        TranslateParameters tps = new TranslateParameters.Builder()
                .source("youdao").from(langFrom).to(langTo).sound(Constants.SOUND_OUTPUT_MP3).voice(Constants.VOICE_BOY_UK).timeout(3000).build();// appkey可以省
        final long start = System.currentTimeMillis();

        translator = Translator.getInstance(tps);
        translator.lookup(input, "requestId", new TranslateListener() {
            @Override
            public void onResult(final Translate result, String input, String requestId) {
                MyApplication.mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        TranslateData td = new TranslateData(
                                System.currentTimeMillis(), result);

                        long end = System.currentTimeMillis();
                        long time = end - start;

                        list.add(td);
                        trslist.add(result);
                        adapter.notifyDataSetChanged();
                        translateList.setSelection(list.size() - 1);
                        dismissLoadingView();
                        imm.hideSoftInputFromWindow(
                                fanyiInputText.getWindowToken(), 0);
                    }
                });
            }

            @Override
            public void onError(final TranslateErrorCode error, String requestId) {
                MyApplication.mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showToast("查询错误:" + error.name());
                        dismissLoadingView();
                    }
                });
            }

            @Override
            public void onResult(List<Translate> results, List<String> inputs, List<TranslateErrorCode> errors, String requestId) {

            }
        });
    }

    /**
     * 显示加载中视图
     *
     * @param text
     */
    private void showLoadingView(final String text) {
        waitHandler.post(new Runnable() {

            @Override
            public void run() {
                if (progressDialog != null && !progressDialog.isShowing()) {
                    progressDialog.setMessage(text);
                    progressDialog.show();
                }
            }
        });

    }

    /**
     * 隐藏加载视图
     */
    private void dismissLoadingView() {
        waitHandler.post(new Runnable() {

            @Override
            public void run() {
                if (progressDialog != null && progressDialog.isShowing())
                    progressDialog.dismiss();
            }
        });

    }

    public void postQuery(final Translate bean) {
        showLoadingView("正在翻译，请稍等");
    }
}
